package org.nearby.note;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.Border;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

import org.nearby.note.bean.note;
import org.nearby.note.dao.noteDaoImpl;
import org.nearby.note.dao.userDaoImpl;
import org.nearby.note.dialog.ClockInDlg;
import org.nearby.note.dialog.ServerStatusDlg;
import org.nearby.note.utils.DbUtil;
import org.nearby.note.utils.common;

public class home extends JFrame implements TreeSelectionListener, ActionListener{
    private TrayIcon trayicon = null;
    private JPanel jp = null;
    private HashMap<String, Integer> d = null;
    private ArrayList<note> notelist = null;
    private noteDaoImpl noteImpl = new noteDaoImpl();
    private JTree jt1 = new JTree();
    private JTextArea jta = new JTextArea();
    private JTextField jt_title = new JTextField();
    private JButton jbut = new JButton("保存");
    
    private JLabel userInfo = new JLabel();

    private int user_id = 0;
    private int note_id = 0;
    
    private userDaoImpl userImpl = new userDaoImpl();

    public home() {
        //this.user_id = userDaoImpl.getUid();
    	this.user_id = 1;
        //userInfo.setText(userDaoImpl.getUserLogin().getUserName());
    	userInfo.setText("登录用户：李建伟");
        //检测用户登录
       /* if(!userDaoImpl.checkIsLogin()){
        	dispose();
        	new login();
        }*/
        initTray();
        initWin();
        initFillData();
        initBind();
    }

    // 系统托盘区
    public void initTray() {
        if (SystemTray.isSupported()) {
            SystemTray tray = SystemTray.getSystemTray();
            Image image = Toolkit.getDefaultToolkit().getImage("icon.gif");
            PopupMenu pop = new PopupMenu();
            MenuItem item1 = new MenuItem("退出");
            MenuItem item2 = new MenuItem("设置");
            MenuItem item3 = new MenuItem("检测更新");

            pop.add(item3);
            pop.add(item2);
            pop.add(item1);

            item1.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });
            item2.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    new settings();
                }
            });

            trayicon = new TrayIcon(image, "我的邻居", pop);
            try {
                tray.add(trayicon);
            } catch (AWTException e) {
                e.printStackTrace();
            }

            trayicon.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    if (e.getButton() == e.BUTTON1) { // 左键
                        setVisible(true);
                        setAlwaysOnTop(true); // 置顶
                        setExtendedState(JFrame.NORMAL); // 恢复
                        setLocationRelativeTo(null);
                    } else if (e.getButton() == e.BUTTON3) { // 右键
                    }
                }
            });

        } else {
            System.out.println("你的系统不支持系统托盘区");
        }
    }

    // 初始化界面
    public void initWin() {
        //窗口设置
        this.setTitle("主窗口");
        this.setLayout(null);
        int winWidth = 500, winHeight = 500;
        this.setSize(winWidth, winHeight);
        //this.setPreferredSize(d);  更好的设置尺寸
        d = common.getWindowCenterSize(winWidth, winHeight);
        this.setLocation(d.get("width"), d.get("height"));
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        userInfo.setBounds(20,20, 480, 30);
        this.add(userInfo);
        
        // 菜单栏
        JMenuBar jb1 = new JMenuBar();
        JMenu m1 = new JMenu("常规操作");
        JMenu m2 = new JMenu("操作一");
        JMenuItem item2 = new JMenuItem("小小便签");

        JMenuItem item3 = new JMenuItem("子操作一");
        JMenuItem item4 = new JMenuItem("子操作二");
        m2.add(item3);
        m2.add(item4);

        m1.add(m2);
        m1.addSeparator();
        m1.add(item2);
        
        JMenu m3 = new JMenu("小工具集");
        JMenuItem  item5 = new JMenuItem("一键启动");
        JMenuItem m4 = new JMenuItem("局域网聊天工具");
        JMenuItem serverStatus = new JMenuItem("服务器状态");
        JMenuItem clockIn = new JMenuItem("打卡");
        
        m3.add(item5);
        m3.add(m4);
        m3.add(serverStatus);
        m3.add(clockIn);
        
        jb1.add(m1);
        jb1.add(m3);
        
        item5.addActionListener(this);
        m4.addActionListener(this);
        serverStatus.addActionListener(this);
        clockIn.addActionListener(this);

        this.setJMenuBar(jb1);
        
        //下部  分割为左右两侧 
        JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false);
        JPanel left = new JPanel(new GridLayout(1, 1));
        JPanel right = new JPanel();
        
     /*   Border b = BorderFactory.createLineBorder(Color.red);
        right.setBorder(b);*/
        
        jsp.setLeftComponent(left);
        jsp.setRightComponent(right);
        jsp.setDividerSize(5);
        jsp.setDividerLocation(150);

        // 左侧  读取现在已有的便签
        notelist = noteImpl.getAllNote(user_id);
        int note_size = notelist.size();
        Object[] os = new Object[note_size];
        for (int i = 0; i < note_size; i++) {
            os[i] = notelist.get(i);
        }
        jt1 = new JTree(os);
        jt1.addTreeSelectionListener(this);
        JScrollPane sp = new JScrollPane(jt1, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        left.add(sp);
        
        //右侧
        JLabel lab1 = new JLabel("标题：");
        lab1.setSize(100, 20);
       
        jt_title.setSize(200, 20);
        
        JLabel lab2 = new JLabel("内容：");
        lab2.setSize(100, 20);
        jta = new JTextArea();
        jta.setSize(200, 100);
      
        right.add(lab1);
        right.add(jt_title);
        right.add(lab2);
        right.add(jta);
        right.add(jbut);
        
        jsp.setBounds(10, 60, 490, 300);
        this.add(jsp);
        this.setVisible(true);
    }
    public void initFillData(){
    	
    }

    // 初始事件绑定
    public void initBind() {
    	 jbut.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent arg0) {
                 note n = new note();
                 n.setUser_id(user_id);
                 n.setNote_id(note_id);
                 n.setNote_title(jt_title.getText());
                 n.setNote_content(jta.getText());
                 
                 if(noteImpl.updateNote(n) == false){
                     JOptionPane.showMessageDialog(null, "操作失败");
                 }else{
                     JOptionPane.showMessageDialog(null, "操作成功");
                     
                     DefaultMutableTreeNode node1 = (DefaultMutableTreeNode)jt1.getLastSelectedPathComponent();
                     node1.setUserObject(n);
                     jt1.updateUI();
                     
                 }
                 
             }
         });
    	 //窗口关闭时，关闭数据库连接
    	 this.addWindowListener(new WindowAdapter() {
    		 public void windowClosing(WindowEvent e){
    			 //清除登录状态
    			 userImpl.deleteSession();
    			 DbUtil.close();
    		 } 
    	 });
    }

    // 左侧树形事件绑定
    @Override
    public void valueChanged(TreeSelectionEvent e) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jt1.getLastSelectedPathComponent();

        note n = (note) node.getUserObject();
        
        jta.setText(n.getNote_content());
        jt_title.setText(n.getNote_title());
        note_id = n.getNote_id();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
         String command = e.getActionCommand();
         if(command.equals( "一键启动")){
             new Fastrun().setVisible(true);
             this.setVisible(false);
         }else if(command.equals("局域网聊天工具")){
        	 new ChatClient().setVisible(true);
        	 this.setVisible(false);
         }else if(command == "服务器状态"){
        	 JDialog serverStatus = new ServerStatusDlg(this, "服务器状态", false);
        	 serverStatus.setVisible(true);
         }else if(command == "打卡"){
        	 JDialog clockIn = new ClockInDlg(this, "打卡", false);
        	 clockIn.setVisible(true);
         }
        
/*        Object o = e.getSource();
        if(o instanceof JMenuItem){
            JMenuItem item = (JMenuItem)o;
            JOptionPane.showMessageDialog(this, item.getText());
        }else if(o instanceof JMenu){
            JMenu menu = (JMenu)o;
            JOptionPane.showMessageDialog(this, menu.getText());
        }*/
        
    }
	public static void main(String[] args) {
		new home();
	}
}
